<?php

namespace app\common\model;

use think\Model;


class Apply extends Model
{

    

    

    // 表名
    protected $name = 'apply';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'agent_area'
    ];
    

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }




    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function level()
    {
        return $this->belongsTo('app\common\model\user\Level', 'level_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function area()
    {
        return $this->belongsTo('Area', 'area_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    protected static function init(){
        self::beforeUpdate(function($row){
            $changed = $row->getChangedData();
            if (array_key_exists('status', $changed) && $row->status=='1') {
                // $ids = $row->team_tag;
                // $ids = explode(',', $ids);
                // if (count($ids) > 1) {
                //     array_pop($ids);
                User::where('id', $row->user_id)->update(['agent_area_id'=>$row->area_id,'level_id'=>$row->level_id,'agent_area_ids'=>$row->area_ids]);
                // }
            }
        });
    }

    public function getAgentAreaAttr($value, $data)
    {
        if(isset($data['area_ids']) && $data['area_ids']){
            $arr = explode(',',$data['area_ids']);
            $area = Area::where('id','in',$arr)->column('id,name');
            // var_dump($area);
            $str = [];
            foreach ($arr as $v) {
                array_push($str,$area[$v]??'');
            }
            return implode(',',$str);
        }
        return '';
    }
}
